package com.example.demo.util.jwt;
import cn.hutool.core.map.MapBuilder;
import cn.hutool.core.map.MapUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public  class JwtUtil {

    public static final String SECRET_KEY = "qwer";

    public static void main(String[] args) {
        String admin = JwtUtil.generateToken("admin");
        System.out.println(admin);
        String usernameFromToken = JwtUtil.getUsernameFromToken(admin);
        System.out.println(usernameFromToken);
        boolean b = JwtUtil.validateToken(admin);
        System.out.println(b);

        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(admin);
        Claims body = claimsJws.getBody();
        Object o = body.get("authorities");
        System.out.println(claimsJws.getBody().getSubject());
        System.out.println(o);
    }


    public static String createToken() {
        return generateToken(SecurityContextHolder.getContext().getAuthentication().getName());
    }
    public static String generateToken(String username) {
        Map<String, Object> claims = new HashMap<>();
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        List<String> authorities = authentication.getAuthorities().stream().map(o -> o.getAuthority()).collect(Collectors.toList());
        claims.put("authorities", authorities);
        Map<String, Object> headers = new  HashMap<>();
        headers.put("type", "jwt");
        return Jwts.builder()
                //头部信息,jwt第一部分内容
                .setHeader(headers)
                //jwt第二部分内容
                .setClaims(claims)
                .setSubject(username)
                //谁签发的
                .setIssuer("zbw")
                //令牌签发时间
                .setIssuedAt(new Date())
                //过期时间
                .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 10)) // 设置过期时间为 10 小时
                .signWith(SignatureAlgorithm.HS512, SECRET_KEY)
                .compact();
    }

    public static boolean validateToken(String token) {
        try {
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static String getUsernameFromToken(String token) {
        Claims claims = Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody();
        return claims.getSubject();
    }
}